<template>
  <div>
    <!-- 动态添加列 -->
    <!-- {{ roleList }} -->
    <el-button type="primary" @click="addColumn">添加列</el-button>
    <el-button type="primary" @click="addRow">添加行</el-button>
    <el-button type="primary" @click="submit">提交</el-button>
    <el-table
      ref="table"
      :data="roleList"
      border
      stripe
      size="mini"
      max-height="700"
      style="margin-top: 20px;width:100%"
    >
      <el-table-column label="试验项目" prop="xm" min-width="100px" fixed="left"></el-table-column>
      <el-table-column label="数量" prop="sl" min-width="100px" fixed="left"></el-table-column>
      <el-table-column label="编号" prop="code" min-width="100px" fixed="right"></el-table-column>
      <el-table-column label="项目" prop="project" min-width="100px" align="center">
        <el-table-column
          v-for="(item, index) in dynamicColumns"
          :key="index"
          :prop="item.prop"
          min-width="300px"
        >
          <template slot="header">
            {{ item.label }}
            <i
              class="el-icon-remove"
              style="color: red; cursor: pointer"
              @click="deleteColunm(index)"
            ></i>
          </template>
          <template slot-scope="scope">
            <el-input v-if="isEdit" v-model="scope.row.custom[item.prop]" placeholder="请输入内容"></el-input>
            <span v-else>{{ scope.row.custom[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [
        {
          id: 1,
          xm: "项目1项目1项目1项目1项目1",
          sl: 10,
          code: 222,
          custom: '{"测试": 1}'
        },
        {
          id: 2,
          xm: "项目2项目2项目2项目2项目2项目2项目2",
          sl: 100,
          code: 333,
          custom: '{"测试": 1, "字段2": "哈哈哈"}'
        },
        {
          id: 3,
          xm: "项目3项目2项目2项目2项目2项目2项目2",
          sl: 100,
          code: 444,
          custom: '{"测试": 1, "字段2": "哈哈哈","字段3":"数据3"}'
        }
      ],
      dynamicColumns: [],
      propArr: [],
      isEdit: true
    };
  },
  created() {},
  mounted() {
    for (let index = 0; index <= 10; index++) {
      this.roleList.push({
        id: index + 3,
        xm: `项目${index}`,
        sl: 100 + index,
        code: 444 + index,
        custom: `{"字段${index}": ${index}, "字段${index +
          1}": "哈哈哈${index}"}`
      });
    }
    this.roleList.forEach(item => {
      if (item.custom) {
        item.custom = JSON.parse(item.custom);
        Object.keys(item.custom).forEach(key => {
          if (this.propArr.indexOf(key) === -1) {
            this.propArr.push(key);
            this.dynamicColumns.push({ prop: key, label: key });
          }
        });
      } else {
        item.custom = {};
      }
    });
  },

  methods: {
    //新增列
    addColumn() {
      this.$prompt("请输入列名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        this.dynamicColumns.push({
          prop: value,
          label: value
        });
      });
    },
    // 新增行
    addRow() {
      const circle = this.roleList[0]; //取出数组中第一个对象
      if (circle) {
        const newObj = {};
        for (let key in circle) {
          //把第一个对象的属性都赋值给新对象newObj  然后每个属性的值都设置为空；
          if (key != "custom") {
            newObj[key] = "";
          } else {
            newObj[key] = {};
          }
        }
        this.roleList.splice(this.roleList.length, 0, newObj);
      }
    },
    // 删除列
    deleteColunm(index) {
      this.dynamicColumns.splice(index, 1);
    },
    submit() {
      let arr = [];
      this.roleList.forEach(data => {
        let temp = {};
        temp.code = data.code;
        temp.xm = data.xm;
        let obj = {};
        this.dynamicColumns.forEach(col => {
          // 仅把有效的列提交
          if (data.custom[col.prop]) {
            obj[col.prop] = data.custom[col.prop];
          }
        });
        if (JSON.stringify(obj) !== "{}") {
          temp.custom = JSON.stringify(obj);
        }
        arr.push(temp);
      });

      console.log(arr);
    },
    // 删除行：并且删除当前行后面所有数据
    deleteRow(index) {
      this.roleList.splice(index, this.roleList.length - index);
    }
  }
};
</script>

<style scoped>
.table-container {
  overflow-x: auto;
}

.el-table__body-wrapper {
  display: flex;
  flex-direction: column-reverse;
}
</style>